<template>
    <PageLayout title="学校数据">
        <template slot="filter">
            <div class="filter-item">
                <div class="filter-item__title">启用状态</div>
                <el-select
                    v-model="setStatus"
                    filterable
                    placeholder="请选择"
                    size="medium"
                    @change="getTableData(1)"
                >
                    <el-option
                        v-for="item in option"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </div>
            <div class="filter-item">
                <div class="filter-item__title">关键词</div>
                <el-input
                    v-model="search"
                    placeholder="请输入内容"
                    size="medium"
                    clearable
                    suffix-icon="el-icon-search"
                    @keyup.native.enter="getTableData(1)"
                    @change="getTableData(1)"
                />
            </div>
            <div class="filter-item">
                <el-button
                    type="primary"
                    size='medium'
                    @click="getTableData(1)"
                >搜索
                </el-button>
            </div>
            <div class="filter-item">
                <el-button
                    type="primary"
                    size='medium'
                    @click="handleSetKy()"
                >客服二维码管理
                </el-button>
            </div>
        </template>
        <!-- table -->
        <el-table
            :data="tableData"
            height="100%"
            ref="tempLateName"
            style="width: 100%;"
            @sort-change="handleSortChanged"
            @select="fnSelect"
            @select-all="fnSelectAllTop"
            @selection-change="handleSelectionChange"
        >
            <el-table-column
                type="selection"
                fixed="left"
            />
            <el-table-column
                label="ID"
                width="100px"
                prop="school_id"
                align="center"
            />
            <el-table-column
                prop="province_name"
                label="省份"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="city_name"
                label="城市"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="school_name"
                label="学校名称"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="college_num"
                label="学院数量"
                show-overflow-tooltip
                align="center"
            >
                <template slot-scope="scope">
                    <el-button
                        size="medium"
                        type="text"
                        @click="fnJump(scope.row)"
                    >
                        {{ scope.row.college_num }}
                    </el-button>
                </template>
            </el-table-column>
            <!--<el-table-column
                prop="status"
                label="状态"
            >
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        :active-value="1"
                        :inactive-value="0"
                        @change="handleUserStatusChange($event, scope.row.school_id)"
                    />
                    <p
                        v-if='scope.row.student_num > 0'
                        class="switch-fixed"
                        @click="fnStopSwitch"
                    />
                </template>
            </el-table-column>-->
            <el-table-column
                prop="student_num"
                label="学校人数"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
                sortable="custom"
                :width="110"
            />
            <el-table-column
                prop="verify_num"
                label="认证人数"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            />
            <el-table-column
                prop="school_group_qrcode"
                label="学校二维码"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
                :width="110"
            >
                <template slot-scope="{row}">
                    <template v-if="!!row.school_group_qrcode">
                        <img
                            :src="row.school_group_qrcode"
                            :style="{
                                width: '40px',
                                height: '40px',
                                cursor: 'pointer'
                            }"
                            @click="fnShowPreview(row.school_group_qrcode)"
                        >
                    </template>
                    <p v-else>
                        --
                    </p>
                </template>
            </el-table-column>
            <el-table-column
                label="群二维码"
                align="center"
                :width="110"
            >
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.school_group_qrcode_status"
                        :active-value="1"
                        :inactive-value="0"
                        @change="setShowQrcode(scope.row)"
                    />
                </template>
            </el-table-column>
            <el-table-column
                prop="tips"
                label="入群文案"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            />
            <el-table-column
                label="校园通讯录"
                align="center"
                :width="110"
            >
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.show_status"
                        :active-value="1"
                        :inactive-value="0"
                        @change="setShowStatus(scope.row)"
                    />
                </template>
            </el-table-column>
            <!--<el-table-column
                prop="apply_num"
                label="申请开启人数"
                sortable="custom"
            >
                <template slot-scope="scope">
                    <span
                        @click="fnUserList(scope.row)"
                        class="curse-add"
                    >{{ scope.row.apply_num }}</span>
                </template>
            </el-table-column>-->
            <el-table-column
                label="操作"
                fixed="right"
                :width="200"
            >
                <template slot-scope="scope">
                    <el-button
                        size="medium"
                        type="text"
                        @click="fnAddSchool(scope.row)"
                    >
                        新增学院
                    </el-button>
                    <el-button
                        size="medium"
                        type="text"
                        @click="uploadCode(scope.row)"
                    >
                        {{ !scope.row.school_group_qrcode ? '上传二维码' : '编辑二维码' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- /table -->
        <template slot="pagination">
            <div
                :style="{
                    display: 'flex',
                    alignItems: 'center'
            }">
                <el-checkbox
                    v-model="checkedAll"
                    :indeterminate="checkIndeterminate"
                    @change="fnChangeChecked"
                >全选</el-checkbox>
                <el-button
                    type="text"
                    :disabled="multipleSelection.length == 0 ? true : false"
                    :style="{marginLeft: '12px'}"
                    @click="handleBatchQrcode(1)"
                >批量开启群二维码</el-button>
                <el-button
                    type="text"
                    :disabled="multipleSelection.length == 0 ? true : false"
                    @click="handleBatchQrcode(2)"
                >批量关闭群二维码</el-button>
                <el-button
                    type="text"
                    @click="handleBatchQrcode(3)"
                >开启所有群二维码</el-button>
                <el-button
                    type="text"
                    @click="handleBatchQrcode(4)"
                >关闭所有群二维码</el-button>
            </div>
            <el-pagination
                background
                layout="total, prev, pager, next"
                :current-page.sync="page.now_page"
                :total="page.total_count"
                :page-size="page.page_size"
                @current-change="getTableData"
            />
        </template>
        <!-- dialog -->
        <el-dialog
            title="新增学院"
            width="530px"
            custom-class="schedule-dialog"
            :visible.sync="showAddDialog"
            :close-on-click-modal="false"
        >
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
            >
                <el-form-item
                    prop='textarea'
                >
                    <el-input
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 7}"
                        placeholder="请输入内容"
                        v-model="ruleForm.textarea"
                    />
                </el-form-item>
            </el-form>
            <div
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    size="medium"
                    type="primary"
                    @click="submitForm('ruleForm')">提交</el-button>
            </div>
        </el-dialog>
        <!-- dialog -->

        <!-- 二维码 -->
        <el-dialog
            title="上传二维码"
            width="600px"
            custom-class="schedule-dialog"
            :visible.sync="showAddDialog2"
            :close-on-click-modal="false"
            class="__upload"
        >
            <div class="__model">
                <div class="__model_items">
                    <p class="__model_title">
                        上传二维码
                    </p>
                    <el-upload
                        :show-file-list="false"
                        :http-request="e=> {fnUploadImageOfGoods(e, true)}"
                        accept="image/*"
                        class="upload-good-image"
                        action="https://jsonplaceholder.typicode.com/posts/"
                    >
                        <img
                            v-if="code_url"
                            :src="code_url"
                            class="avatar">
                        <p
                            class="upload-hide"
                            v-else
                        >
                            <i class="el-icon-plus"/>
                        </p>
                    </el-upload>
                </div>
                <!-- <template v-if="TYPE == 2">
                    <div
                        class="__model_items"
                        :style="{marginTop: '32px'}"
                    >
                        <p class="__model_title">
                            入群文案
                        </p>
                        <el-input
                            type="textarea"
                            placeholder="请输入内容"
                            v-model="code_desc"
                            show-word-limit
                            :autosize="{ minRows: 4, maxRows: 6}"
                        />
                    </div>
                </template> -->
                <div
                    class="__model_items"
                    :style="{marginTop: '32px'}"
                >
                    <p class="__model_title">
                        二维码状态
                    </p>
                    <el-switch
                        v-model="code_status"
                        active-text="开启"
                        inactive-text="关闭"/>
                </div>
            </div>
            <div class="__foot">
                <el-button
                    size="small"
                    type="default"
                    :style="{width: '120px', marginRight: '24px'}"
                    @click="showAddDialog2 = false"
                >
                    取消
                </el-button>
                <el-button
                    size="small"
                    type="primary"
                    :style="{width: '120px'}"
                    :disabled="!code_url"
                    @click="handleConfirm()"
                >
                    确定
                </el-button>
            </div>
        </el-dialog>

        <img-preview ref="preview" />
    </PageLayout>
</template>

<script>
import {back} from "@/mixin/back";
import imgPreview from '@/components/common/img-preview';

export default {
    components: {
        imgPreview
    },
    mixins: [back],
    data () {
        return {
            checkIndeterminate: false,
            multipleSelection: [],
            checkedAll: false,
            setStatus: '',
            option: [{
                value: '',
                label: '全部'
            }, {
                value: '0',
                label: '未启用'
            }, {
                value: '1',
                label: '启用'
            }],
            search: '',
            school_id: '',
            tableData: [],
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            showAddDialog: false,
            ruleForm: {
                textarea: '',
            },
            rules: {
                textarea: [
                    { required: true, message: '请填写学院名称', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入学校名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ]
            },
            filterData: {
                sort_field: '',
                sort_type: ''
            },
            // 上传二维码
            TYPE: 1,//1 群二维码 2 客服二维码
            showAddDialog2: false,
            code_url: '',
            code_desc: '',
            code_status: false
        };
    },
    created () {
        this.setHeader();
        this.getTableData();
    },
    methods: {
        /**
         * 设置表单header
         */
        setHeader () {
            this.$store.commit('SET_HEADER', [{
                title: "APP后台",
            },
            {
                title: '社交'
            },
            {
                title: "学校数据"
            }]
            );
        },

        /**
         * 获取表格数据
         */
        getTableData (page) {
            this.$post('/student/forum%5Cget_list', {
                page_id: page || this.page.now_page,
                status: this.setStatus,
                keyword: this.search,
                sort_field: this.filterData.sort_field,
                sort_type: this.filterData.sort_type
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                }
            });
        },

        /**
         * @description 获取客服二维码
         */
        handleSetKy () {
            this.TYPE = 2;
            this.getKfConfig().then(resp => {
                // 编辑
                if(!!resp.kf_qrcode) {
                    this.code_url = resp.kf_qrcode;
                    // this.code_desc = resp.tips;
                    this.code_status = !!resp.status ? true : false;
                } else { //新增
                    this.kf_qrcode = this.code_url = this.code_desc = '';
                }
                this.showAddDialog2 = true;
            });
        },

        /**
         * @description 上传/编辑二维码
         */
        uploadCode (row) {
            this.TYPE = 1;
            this.school_id = row.school_id;
            // 上传
            if(!row.school_group_qrcode) {
                this.code_url = this.code_desc = '';
            } else { //编辑
                this.code_url = row.school_group_qrcode;
                // this.code_desc = row.tips;
                this.code_status = !!row.school_group_qrcode_status && row.school_group_qrcode_status !== null ? true : false;
            }
            this.showAddDialog2 = true;
        },

        /**
         * @description 确定上传
         */
        handleConfirm () {
            if(this.TYPE == 1) {
                this.$post('/student/forum%5Cset_school_info', {
                    school_id: this.school_id,
                    school_group_qrcode: this.code_url,
                    // tips: this.code_desc
                    school_group_qrcode_status: this.code_status ? 1 : 0
                }, resp => {
                    if (resp.code == 1) {
                        this.showAddDialog2 = !this.showAddDialog2;
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '设置成功'
                        });
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'warning',
                            message: resp.msg
                        });
                    }
                });
            } else {
                this.$post('/student/forum%5Cset_kf_config', {
                    kf_qrcode: this.code_url,
                    // tips: this.code_desc,
                    status: this.code_status ? 1 : 0
                }, resp => {
                    if (resp.code == 1) {
                        this.showAddDialog2 = !this.showAddDialog2;
                        this.$message({
                            type: 'success',
                            message: '设置成功'
                        });
                        this.getTableData();
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'warning',
                            message: resp.msg
                        });
                    }
                });
            }
        },

        /**
         * @description 设置群二维码状态
         */
        setShowQrcode (row) {
            this.$post('/student/forum%5Cset_school_info', {
                school_id: row.school_id,
                school_group_qrcode: row.school_group_qrcode,
                school_group_qrcode_status: row.school_group_qrcode_status
            }, resp => {
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '设置成功'
                    });
                    this.getTableData();
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * @description 批量设置群二维码
         * @type 1:批量开启 2:批量关闭 3:开启全部 4:关闭全部
         */
        handleBatchQrcode (type) {
            let school_ids = '';

            if(!!this.multipleSelection.length) {
                school_ids = this.multipleSelection.reduce((cur,next) => {
                    cur.push(next.school_id);
                    return cur;
                }, []);
            }

            this.$post('/student/forum%5Cbatch_set_qrcode_status', {
                school_ids: !!school_ids.length ? school_ids.join() : '',
                school_group_qrcode_status: type == 1 || type == 3 ? 1 : 0
            }, resp => {
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '设置成功'
                    });
                    this.getTableData();
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * @description 获取客服二维码
         */
        getKfConfig () {
            return new Promise((resolve,reject) => {
                this.$post('/student/forum%5Cget_kf_config', {}, resp => {
                    if (resp.code == 1) {
                        resolve(resp.data);
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'warning',
                            message: resp.msg
                        });
                    }
                });
            });
        },

        /**
         * 上传图片
         */
        fnUploadImageOfGoods(e) {
            this.fnUploadImage(e, (resp) => {
                this.code_url = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },

        fnShowPreview(images) {
            let imgList = [];

            if (typeof(images) == 'object') {
                this.$refs.preview.show(images);
            } else if (typeof(images) == 'string') {
                imgList.push(images);
                this.$refs.preview.show(imgList);
            }
        },

        /**
         * 阻止禁用
         */
        fnStopSwitch () {
            this.$message({
                type: 'warning',
                message: '学校人数不为0，不可禁用'
            });
            return;
        },

        /**
         * 设置用户状态
         */
        handleUserStatusChange(status, school_id) {

            this.$post('/student/forum%5Cset_status', {
                school_id,
                status
            }, resp => {
                if (resp.code == 1) {
                    if (status == 1) {
                        this.$message({
                            type: 'success',
                            message: '该学校已开通社区'
                        });
                    } else if (status == 0) {
                        this.$message({
                            message: '该学校未开通社区',
                            type: 'warning'
                        });
                    }
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        messaeg: resp.msg
                    });
                }
            });
        },

        /**
         * 新增学院
         */
        fnAddSchool (row) {
            this.showAddDialog = !this.showAddDialog;
            this.school_id = row.school_id;
        },

        /**
         * 提交学校数据
         */
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$post('/student/region_college%5Ccreate', {
                        school_id: this.school_id,
                        college_name_str: this.ruleForm.textarea
                    }, resp => {
                        if (resp.code == 1) {
                            this.showAddDialog = !this.showAddDialog;
                            this.getTableData();
                            this.$message({
                                type: 'success',
                                message: '添加成功'
                            });
                        } else if (resp.code == 0) {
                            this.$message({
                                type: 'warning',
                                message: resp.msg
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        /**
         * 跳转学院数据列表
         */
        fnJump (row) {
            const school_id = row.school_id;

            this.$router.replace({
                name: 'SocialCollege',
                query: {
                    school_id
                }
            });
        },

        /**
         * 跳转申请用户列表
         */
        fnUserList (row) {
            const school_id = row.school_id;

            this.$router.replace({
                name: 'SocialApply',
                query: {
                    school_id
                }
            });
        },

        /**
         * 排序
         */
        handleSortChanged(data) {
            let sortTypeMap = {
                ascending: 'asc',
                descending: 'desc'
            };

            let sortFieldMap = {
                "student_num": 'student_num',
                "apply_num": 'apply_num'
            };

            if (data.order) {
                this.filterData.sort_field = sortFieldMap[data.prop];
                this.filterData.sort_type = sortTypeMap[data.order];
            } else {
                this.filterData.sort_field = '';
                this.filterData.sort_type = '';
            }

            this.getTableData();
        },

        /**
         * @description 全选逻辑操作
         */
        fnSelect(selection) {
            if(selection.length == this.tableData.length) {
                this.checkedAll = true;
            }else{
                this.checkedAll = false;
            }
            if(selection.length > 0 && selection.length < this.tableData.length) {
                this.checkIndeterminate = true;
            }else{
                this.checkIndeterminate = false;
            }
        },
        fnSelectAllTop(selection) {
            if(selection.length > 0) {
                this.checkedAll = true;
            }else{
                this.checkedAll = false;
            }
            if(selection.length > 0 && selection.length < this.tableData.length) {
                this.checkIndeterminate = true;
            }else{
                this.checkIndeterminate = false;
            }
        },
        fnChangeChecked() {
            if(this.checkedAll){
                this.toggleSelection(1);
            }else{
                this.toggleSelection();
            }
        },
        toggleSelection(rows) {
            if (rows) {
                this.$refs.tempLateName.toggleAllSelection();
            } else {
                this.$refs.tempLateName.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        /**
         * 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        },

        /**
         * 设置校园通讯录显示状态
         * @param row
         */
        setShowStatus(row) {
            let params = {
                school_id: row.school_id,
                show_status: row.show_status
            };

            this.$post('/student/forum%5Cset_student_contact_show_status', params, resp => {
                if (resp.code === 1) {
                    this.getTableData();
                    this.$notify({
                        title: '提示',
                        type: 'success',
                        message: '操作成功'
                    });
                } else {
                    this.$notify({
                        title: '提示',
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        }
    }
};
</script>

<style lang="less" scoped>
.dialog-footer {
    display: flex;
    justify-content: center;
    align-items: center;
}
.__upload {
    .__model {
        margin: 0 42px;
        margin-bottom: 24px;
        .__model_items {
            display: flex;
            flex-direction: column;
            .__model_title {
                font-size: 14px;
                font-weight: 500;
                color: rgba(51,51,51,1);
                margin-bottom: 18px;
            }
        }
    }
    .__foot {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 10px;
    }
    .upload-good-image{
        border: 1px solid red;
        width: 100px;
        height: 100px;
        display: flex;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        align-items: center;
        justify-content: center;
        font-size: 34px;
        color: #8c939d;
        img{
            width: 100px;
            height: 100px;
        }
        .upload-hide {
            width: 100px;
            height: 100px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}
</style>
